package com.ayu.shortlink.settlement.service.handler.strategy;

import com.alipay.api.kms.aliyun.exceptions.ClientException;
import com.ayu.shortlink.settlement.service.bases.strategy.AbstractDiscountStrategy;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 扣减策略选择容器组件
 */
@Component
@Slf4j
public class DiscountStrategyContext implements CommandLineRunner, ApplicationContextAware {
    // 扣减策略容器Map
    private final Map<Integer, AbstractDiscountStrategy> STRATEGY_CHOOSE_MAP = new HashMap<>();
    private ApplicationContext applicationContext;
    @Override
    public void run(String... args) throws Exception {
        // 进行装配
        Map<String, AbstractDiscountStrategy> beans = applicationContext.getBeansOfType(AbstractDiscountStrategy.class);
        beans.forEach((k,v) -> {
            STRATEGY_CHOOSE_MAP.put(v.mark(), v);
        });
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @SneakyThrows
    public BigDecimal handler(Integer discountType,BigDecimal totalAmount,Map consumeRule){
        AbstractDiscountStrategy strategy = STRATEGY_CHOOSE_MAP.get(discountType);
        if (strategy == null){
            throw new ClientException("策略选择错误");
        }
        return strategy.handler(totalAmount, consumeRule);
    }
}